import paramiko
import settings
import requests
from concurrent.futures import ThreadPoolExecutor
from utils.hardware import get_host_msg


def my_ssh(hostname, cmd):
    ssh1 = paramiko.SSHClient()
    ssh1.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh1.connect(hostname=hostname, port=settings.SSH_PORT, username=settings.SSH_USERNAME,
                 password=settings.SSH_PASSWORD)
    stdin, stdout, stderr = ssh1.exec_command(cmd)
    result = stdout.read()
    ssh1.close()

    return result.decode('utf-8')


def get_host_list():
    response = requests.get(url=settings.GET_HOST_LIST)
    response_list = [item.get('hostname') for item in response.json()]
    return response_list  # 返回一个列表，包含 host


def task(host):
    host_msg = get_host_msg(my_ssh, host)  # 获取主机信息
    result = requests.post(
        url=settings.POST_HOST_MSG,
        json={'host': host, 'info': host_msg}
    )
    print(result)


def run():
    host_list = get_host_list()
    pool = ThreadPoolExecutor(10)
    for host in host_list:
        pool.submit(task, host)


if __name__ == '__main__':
    run()
